
var final_url = null;

/**
 * 网络请求
 * @param {string} url 请求url
 * @param {obj} body json对象
 * @param {string} method get/post
 * @returns Promise<obj>
 */
async function request (url, body, method, headers) {
    if (!method) {
        method = 'GET';
    }
    if (!body) {
        body = {};
    }
    return await http.fetch(url, { body: http.Body.json(body), method, headers });
}

async function note_request (url, body, method) {
    if (!url.startsWith('/')) {
        final_url += '/';
    }
    final_url += url;
    return await request(final_url, body, method, { "j-tk": get_token() });
}

function get_token () {
    return localStorage['jken'];
}

function set_token (token) {
    localStorage['jken'] = token;
}


async function read_config () {
    if (final_url) {
        return;
    }

    try {
        const text = await fs.readTextFile('config.json', { dir: fs.BaseDirectory.Resource });
        if (!text) {
            final_url = 'http://127.0.0.1:7879';
            return;
        }
        let config = JSON.parse(text);
        if (!config) {
            final_url = 'http://127.0.0.1:7879';
            return;
        }

        console.debug(config);
        final_url = config.server_url;
    } catch (error) {
        console.error(error);
        final_url = 'http://127.0.0.1:7879';
    }
}